package com.soujiayi.util;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import org.xmlpull.v1.XmlPullParser;


import android.content.Context;
import android.util.Log;
import android.util.Xml;

public class CityParser {

	private Context context;
	private List<LinkedHashMap<String, Object>> listMap;

	public CityParser(Context context) {
		this.context = context;
	}

	public List<LinkedHashMap<String, Object>> getCities() {
		try {
			XmlPullParser xpp = Xml.newPullParser();;
			xpp.setInput(context.getResources().getAssets().open("cities.xml"), "UTF-8");
			
			listMap = new ArrayList<LinkedHashMap<String, Object>>();
			LinkedHashMap<String, Object> map = null;
			List<String> list = null;
			int xmlEventType;
			String type = null;
			
			while ((xmlEventType = xpp.next())!= XmlPullParser.END_DOCUMENT) {
				if (xpp.getEventType() == XmlPullParser.START_TAG
						&& "category".equals(xpp.getName())) {
					type = xpp.getAttributeValue(null, "type");
					list = new ArrayList<String>();
				} else if (xmlEventType == XmlPullParser.START_TAG
						&& "city".equals(xpp.getName()) && type != null) {
					list.add(xpp.nextText());
				} else if (xpp.getEventType() == XmlPullParser.END_TAG
						&& "category".equals(xpp.getName()) && type != null) {
					map = new LinkedHashMap<String, Object>();
					map.put("type", type);
					map.put("list", list);
					listMap.add(map);
				}
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return listMap;
	}

}
